﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.OracleClient;
using System.Data;
using System.Configuration;
using log4net;



namespace Service.ZSJL.Com.Data.OracleDNet
{
    public abstract class BaseDao
    {

        ILog log = LogManager.GetLogger(typeof(BaseDao));
        public BaseDao(string connstr)
        {
            //
            // TODO: Add constructor logic here
            //
            this.ConnectStr = connstr;
            dacs = new DataAccess(ConnectStr);
            // log = LogManager.GetLogger(typeof(BaseDao));
        }

        public BaseDao()
        {
            // log = LogManager.GetLogger(BaseDao);
            dacs = new DataAccess(ConnectStr);
        }

        private string _ConnectStr = "";

        public string ConnectStr
        {
            get { return _ConnectStr; }
            set { _ConnectStr = value; }
        }

        private static OracleTransaction trans = null;
        public abstract String TableName { get; }
        public abstract String KeyName { get; }
        public DataAccess dacs = null;
        public DataTable FindBySql(string wheres)
        {
            string sql = "select * from {0} where  1=1  ";
            sql = string.Format(sql, TableName);
            sql += wheres;

            return dacs.DataTable(sql);
        }


        public DataTable ExcuteSql(string sql)
        {
            return dacs.DataTable(sql);
        }
        //protected DataTable page(string sql)
        //{


        //    return dacs.DataTable(sql);
        //}
        protected DataTable FindFirstSql(string wheres, int count)
        {
            string sql = "select top {0} * from {1} where  1=1 ";
            sql = string.Format(sql, count, TableName);
            sql += wheres;

            return dacs.DataTable(sql);
        }
        public object FindColumnBySql(string wheres, string colName)
        {
            string sql = "select {1} from {0} where  1=1 ";
            sql = string.Format(sql, TableName, colName);
            sql += wheres;
            return dacs.ExecuteScalar(sql);
        }


        public bool Add(DataRow row)
        {

            DataColumnCollection cos = row.Table.Columns;
            DataColumnCollection cos2 = null;
            StringBuilder cols = new StringBuilder();
            StringBuilder vals = new StringBuilder();
            string split = ",";

            if (!string.IsNullOrEmpty(TableName))
            {
                string wh = " and 1=2 ";
                DataTable dt = FindBySql(wh);
                cos2 = dt.Columns;

            }
            else return false;

            for (int i = 0; i < cos.Count; i++)
            {
                if (cos2.Contains(cos[i].ColumnName) && !string.IsNullOrEmpty(row[i] + ""))
                {
                    cols.Append(cos[i].ColumnName + split);
                    if (cos[i].DataType == typeof(DateTime))
                        vals.Append("to_date('" + row[i] + "','yyyy-mm-dd hh24:mi:ss'),");
                    else if (cos[i].DataType == typeof(string))
                        vals.Append("'" + row[i] + "',");
                    else
                        vals.Append(row[i] + split);

                }
            }
            cols.Remove(cols.Length - 1, 1); vals.Remove(vals.Length - 1, 1);


            string sql = "insert into  {2} ({0}) values({1}) ";
            sql = string.Format(sql, cols, vals, TableName);
            return dacs.ExecuteSql(sql) > 0;
        }
        public bool Add(DataTable dt)
        {
            foreach (DataRow r in dt.Rows)
            {
                Add(r);
            }
            return true;

        }

        private bool Add(DataRow[] rws)
        {
            foreach (DataRow r in rws)
            {
                Add(r);
            }
            return true;

        }
        public bool Update(DataTable dt)
        {
            foreach (DataRow r in dt.Rows)
            {
                if (r.RowState == DataRowState.Modified)
                    Update(r);
            }
            return true;
        }

        public bool Update(DataRow[] drs)
        {
            foreach (DataRow r in drs)
            {
                Update(r);
            }
            return true;
        }
        public bool Update(DataRow row)
        {
            DataColumnCollection cos = row.Table.Columns;
            DataColumnCollection cos2 = null;
            string split = ",";
            StringBuilder vals = new StringBuilder();

            if (!string.IsNullOrEmpty(TableName))
            {
                string wh = " and 1=2 ";
                DataTable dt = FindBySql(wh);
                cos2 = dt.Columns;

            }
            else return false;



            for (int i = 1; i < cos.Count; i++)
            {
                if (cos2.Contains(cos[i].ColumnName))
                {
                    ///  cols.Append(cos[i].ColumnName + split);  && cos[i].ColumnName != "CHK"
                    if (cos[i].DataType == typeof(string))
                    {
                        if (!string.IsNullOrEmpty(row[i] + ""))
                            vals.Append(cos[i].ColumnName + "='" + row[i] + "',");
                    }
                    else if (cos[i].DataType == typeof(DateTime))
                    {
                        if (!string.IsNullOrEmpty(row[i] + ""))
                            vals.Append(cos[i].ColumnName + "=" + "to_date('" + row[i] + "','yyyy-mm-dd hh24:mi:ss'),");
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(row[i] + ""))
                            row[i] = 0;
                        vals.Append(cos[i].ColumnName + "=" + row[i] + split);
                    }

                }

            }

            string sql = "update {0} set {1}  where {2}='{3}'";
            if (!string.IsNullOrEmpty(vals.ToString()))
                vals.Remove(vals.Length - 1, 1);
            sql = string.Format(sql, TableName, vals, KeyName, row[KeyName]);
            log.Debug(sql);
            return dacs.ExecuteSql(sql) > 0;
        }


        public bool Update(string vals, string col_vals)
        {
            string sql = "update {0} set {1}  where {2}";

            sql = string.Format(sql, TableName, vals, col_vals);
            log.Debug(sql);
            return dacs.ExecuteSql(sql) > 0;


        }
        public bool Update(DataRow row, string col_vals)
        {
            DataColumnCollection cos = row.Table.Columns;
            DataColumnCollection cos2 = null;
            string split = ",";
            StringBuilder vals = new StringBuilder();

            if (!string.IsNullOrEmpty(TableName))
            {
                string wh = " and 1=2 ";
                DataTable dt = FindBySql(wh);
                cos2 = dt.Columns;

            }
            else return false;



            for (int i = 0; i < cos.Count; i++)
            {
                if (cos2.Contains(cos[i].ColumnName))
                {
                    ///  cols.Append(cos[i].ColumnName + split);  && cos[i].ColumnName != "CHK"
                    if (cos[i].DataType == typeof(string))
                    {
                        if (!string.IsNullOrEmpty(row[i] + ""))
                            vals.Append(cos[i].ColumnName + "='" + row[i] + "',");
                    }
                    else if (cos[i].DataType == typeof(DateTime))
                    {
                        if (!string.IsNullOrEmpty(row[i] + ""))
                            vals.Append(cos[i].ColumnName + "=" + "to_date('" + row[i] + "','yyyy-mm-dd hh24:mi:ss'),");
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(row[i] + ""))
                            vals.Append(cos[i].ColumnName + "=" + row[i] + split);
                    }

                }

            }


            if (!string.IsNullOrEmpty(vals.ToString()))
                vals.Remove(vals.Length - 1, 1);

            return Update(vals.ToString(), col_vals);
        }


        public bool DeleteById(string id)
        {
            string sql = "delete FROM {2} where  {0}={1} ";
            sql = string.Format(sql, KeyName, id, TableName);

            return dacs.ExecuteSql(sql) > 0;
        }

        public DataTable FindById(string id)
        {
            string sql = " and  {0}='{1}' ";
            sql = string.Format(sql, KeyName, id);
            return FindBySql(sql);
        }

        public DataTable FindAll()
        {

            return FindBySql("");
        }

        protected abstract OracleCommand[] comms { get; }

        public bool AddOrUpdate(DataTable dt)
        {
            Add(dt.Select("", "", DataViewRowState.Added));
            Update(dt.Select("", "", DataViewRowState.ModifiedCurrent));
            return true;

        }



        public void BeginTransaction()
        {

            trans = dacs.BeginTrans();


        }


        public void RollBack()
        {

            trans.Rollback();
            trans.Dispose();
            trans = null;

        }
        public void CommitTrans()
        {

            trans.Commit();
            trans.Dispose();
            trans = null;

        }
        public void Close()
        {
            dacs.closeConnection();

        }






    }
}
